<?php
/*
# ------------------------------------------------------------------------
# JA Job Board Package
# ------------------------------------------------------------------------
# Copyright (C) 2004-2010 JoomlArt.com. All Rights Reserved.
# @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
# Author: JoomlArt.com
# Websites: http://www.joomlart.com - http://www.joomlancers.com.
# ------------------------------------------------------------------------
*/

jimport( 'joomla.application.component.model' );

/**
 * @package Joomla
 * @subpackage JobBoard
 */
class JAJobBoardModelJAFieldList extends JModel
{
    var $_data;
    var $_table;
    var $_pagination;
    /**
    * Return the query is used to retrive all row from database
    * @return string The query is used 
    */
    function _buildQuery(){
    	global $mainframe, $option;
    	
    	$db = &JFactory::getDBO();
    	
    	$filter_table		= $mainframe->getUserStateFromRequest( $option ."jafieldlist.filter_table",		'filter_table',		'',	'word' );
		
        $where = array();
		
		if($filter_table){
			$where[] = " f.table_name = ". $db->Quote( $filter_table, false );
		}
		
		$where_clause = "";
		if(count($where)){
		    $where_clause = " WHERE ". implode(' and ', $where);
		}
		
        $query = "select * from #__ja_form_fields as f"
            	. $where_clause
            	. "ORDER BY field_ordering"
        	;
        
        return $query;
    }
    
    /**
    * Get field table instance
    * @return JTable Configuration table object
    */
    function &_getTable(){
        if($this->_table == null){
        	$this->_table = &JTable::getInstance('JA_FieldList', 'JobBoardTable');
		}
		return $this->_table;
	}
	
	/**
	* Get page navigator object
	* @return 
	*/
	function &getPagination(){
		if ($this->_pagination == null) {
			$this->getItems();
		}
		return $this->_pagination;
	}
	
	/**
	* Remove field record
	* @return Number of removed records
	*/
	function remove($task = 'remove'){
	    $cid = JRequest::getVar('cid',array(), 'post', 'array');
	    $n =  count($cid);
	    JArrayHelper::toInteger( $cid );
	    
	    if($n){
	        if($task == 'remove')
				$query = "DELETE FROM #__ja_form_lists WHERE id = ". implode(" OR id = ", $cid);
	        
			$db = &JFactory::getDBO();
	        $db->setQuery($query);
	        if($db->query()){
	            $table = $this->_getTable();
	            $table->reorder();
	            return $n;
			}
		}
		
		return 0;
	}

	
	/**
	 * Reorder field list item
	 *
	 * @param int $item	The id of the item
	 * @param int $movement Movement direction
	 * @return void
	 */
	function orderItem($item, $movement){
		global $mainframe, $option;
    	
    	$filter_table		= $mainframe->getUserStateFromRequest( $option .".jafieldlist.filter_table",		'filter_table',		'ja_profiles',	'word' );
		
    	$row = &$this->_getTable();
	    $row->load($item);
		if(!$row->move($movement, $filter_table)){
			$this->setError($row->getError());
			return false;
		}
		return true;
	}
	
	function setOrder($items){
		$total		= count( $items );
		$row		=& $this->_getTable();

		$order		= JRequest::getVar( 'ordering', array(), 'post', 'array' );
		JArrayHelper::toInteger($order);

		// update ordering values
		for( $i=0; $i < $total; $i++ ) {
			$row->load( $items[$i] );
			// track parents
			if ($row->ordering != $order[$i]) {
				$row->ordering = $order[$i];
				if (!$row->store()) {
					$this->setError($row->getError());
					return false;
				}
			} // if
		} // for
		
		return true;
	}
	
	/**
	* Get configuration item
	* @return JTable Table object
	*/
	function getItem(){
		static $item;
		if (isset($item)) {
			return $item;
		}

		$table =& $this->_getTable();

		// Load the current item if it has been defined
		$edit	= JRequest::getVar('edit',true);
		$cid = JRequest::getVar( 'cid', array(0), '', 'array' );
		JArrayHelper::toInteger($cid, array(0));
		
		if ($edit) {
			$table->load($cid[0]);
		}
		
	    $item = $table;
	    return $item;	    
	}
	
	function getItems(){
		global $mainframe, $option;

		$filter_table		= $mainframe->getUserStateFromRequest( $option .".jafieldlist.filter_table",		'filter_table',		'ja_profiles',	'word' );
		$filter_order		= $mainframe->getUserStateFromRequest( $option .".jafieldlist.filter_order",		'filter_order',		'fl.ordering',	'cmd' );
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( $option .".jafieldlist.filter_order_Dir",	'filter_order_Dir',	'ASC',			'word' );
		$search				= $mainframe->getUserStateFromRequest( $option .".jafieldlist.search",			'search',			'',				'string' );
		$search				= JString::strtolower( $search );
	    $limit				= $mainframe->getUserStateFromRequest( 'global.list.limit',							'limit',			$mainframe->getCfg( 'list_limit' ),	'int' );
		$limitstart			= $mainframe->getUserStateFromRequest( $option.'.jafieldlist.limitstart',		'limitstart',		0,				'int' );
		if(!in_array($filter_order, array('fl.id', 'fl.field_id', 'ff.label', 'ff.field_name', 'ff.field_type', 'ff.is_required', 'fl.ordering'))){
		    $filter_order = 'fl.ordering';
		}
        
		$db = &JFactory::getDBO();
       
		// just in case filter_order get's messed up
		if ($filter_order) {
			$orderby = ' ORDER BY '.$filter_order .' '. $filter_order_Dir . ', ff.table_name';
		} else {
			$orderby = ' ORDER BY ff.table_name, fl.ordering ';
		}
		
		$where = array();
		if($search){
		    $where[] = " ((ff.field_name LIKE ". $db->Quote( '%'.$db->getEscaped( $search, true ).'%', false ).")"
		    	." OR (ff.label LIKE ". $db->Quote( '%'.$db->getEscaped( $search, true ).'%', false )."))";
		}
		
		if($filter_table){
			$where[] = " ff.table_name = ". $db->Quote( $filter_table, false );
		}
		
		$where_clause = "";
		if(count($where)){
		    $where_clause = " WHERE ". implode(' and ', $where);
		}

		$query = "SELECT fl.id, fl.field_id, ff.label, ff.field_name, ff.field_type, ff.is_required, fl.ordering, fl.checked_out "
			." FROM #__ja_form_lists AS fl "
			." LEFT JOIN #__ja_form_fields AS ff ON fl.field_id = ff.id"
			. $where_clause
            . $orderby;
		$db->setQuery($query);
		//echo $db->getQuery($query);exit;
		$items = $db->loadObjectList();

		$total = count( $items );

		jimport('joomla.html.pagination');
		$this->_pagination = new JPagination( $total, $limitstart, $limit );
		
		// slice out elements based on limits
		$list = array_slice( is_array($items)? $items : array(), $this->_pagination->limitstart, $this->_pagination->limit );
	
		
		return $list;
	}	
	
	/**
	* Checkout item
	* 
	*/
	function checkout($uid = null){
		$id = JRequest::getVar('cid', array(0), '', 'array');
		JArrayHelper::toInteger( $id, array(0) );

		// Make sure we have a user id to checkout the article with
		if (is_null($uid)) {
			$user	=& JFactory::getUser();
			$uid	= $user->get('id');
		}

		// Lets get to it and checkout the thing...
		$item	= $this->getItem();
		if(!$item->checkout($uid, $id[0])) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		return true;
	}
	
	/** 
	* Store configuration item
	* @param array The post array
	*/
	function store(){
		global $mainframe, $option;
		$filter_table		= $mainframe->getUserStateFromRequest( $option .".jafieldlist.filter_table",		'filter_table',		'ja_profiles',	'word' );

		// Initialize variables
		$db		=& JFactory::getDBO();
		$row	=& $this->getItem();
		$post	= JRequest::get('request');
		
		
		if (!$row->bind( $post )) {
			echo "<script> alert('Bind Error:".$row->getError(true)."'); window.history.go(-1); </script>\n";
			return false;
		}
		
		if (!$row->check())
		{
			echo "<script> alert('Check Error:".$row->getError(true)."'); window.history.go(-1); </script>\n";
			return false;
		}
        
		if (!$row->store())
		{
			echo "<script> alert('Store Error:".$row->getError(true)."'); window.history.go(-1); </script>\n";
			return false;
		}
		$row->reorder($filter_table);
		$row->checkin($row->id);

		return $row->id;
	}
	
	/**
	* Get the list of field in its order
	* @param $table Get field list of the table. All fields will be selected if this parameter is null or empty
	* @return array 
	*/
	function getFieldList(){
		global $mainframe, $option;
    	
    	$db = &JFactory::getDBO();
    	
    	$filter_table		= $mainframe->getUserStateFromRequest( $option .".jafieldlist.filter_table",		'filter_table',		'ja_profiles',	'word' );
    			
		if(empty($filter_table))
			return;
		
		// select all fields are already in ja_form_lists
		$query = "SELECT field_id FROM #__ja_form_lists AS fl "
			." LEFT JOIN #__ja_form_fields AS ff ON fl.field_id = ff.id"
			." WHERE ff.table_name = '$filter_table'";
		$db->setQuery($query);
		$fieldIDs = $db->loadResultArray();

		$query = "SELECT id, field_ordering, label FROM #__ja_form_fields " 
			." WHERE table_name = '$filter_table' "
			.(count($fieldIDs)? " AND id NOT IN (". implode(', ', $fieldIDs) .")" : "")
			."ORDER BY field_ordering";
		$db->setQuery($query);
		$fields = $db->loadObjectList();

		return $fields;
	}
	
	function getField(){
		$fid = JRequest::getVar('fid', '0');
		$db = JFactory::getDBO();
		$query = "SELECT field_name, label FROM #__ja_form_fields WHERE id = '$fid' ";
        $db = &JFactory::getDBO();
        $db->setQuery($query, 0, 1);
        $field = $db->loadObject();
        return $field;
	}
}
?>